﻿#include "HP_Modbus.h"
#include <QDir>
#include <QDebug>
#include <QTimer>

AcqPressure::AcqPressure()
{  
    isConnect=false;
}

AcqPressure::~AcqPressure()
{

}

bool AcqPressure::Connect()
{
    if(!isRunning())
    {
        this->start();
        return  true;
    }
    else
    {
        return  false;
    }
}

bool AcqPressure::DisConnect()
{
    if(!isRunning())
        return true;
    isBreakThread=true;
    int delayCunt=0;
    while(isBreakThread)
    {
        delaymsec(10);
        delayCunt++;
        if(delayCunt>300)   //延时3秒
        {
            return false;
        }
    }
    wait();
    return  true;
}

void AcqPressure::SetParam(QByteArray buff)
{
    SendParambuff=buff;
    isSetParam=true;
}


void AcqPressure::run()
{
    isConnect=false;
    recvbuff.clear();
    //m_Tcp = modbus_new_tcp("127.0.0.1", 502);
    p_modbus=modbus_new_rtu(s_HP.Port.toStdString().data(), s_HP.BaudRate, s_HP.Parity, s_HP.DataBits, s_HP.StopBits);
    modbus_set_slave(p_modbus, 1);
    if (modbus_connect(p_modbus) >= 0)
    {
        modbus_set_response_timeout(p_modbus, 1, 200000);	//超时200ms
    }
    else
    {
        return;
    }
    //设置频率
    QDateTime lastTime = QDateTime::currentDateTime();

    //设置超时
    int outTime=0;
    while(1)
    {
        delaymsec(3);
        if(isBreakThread)
        {
            isBreakThread=false;
            break;
        }

        //是否开始
        if(!isStart) continue;
        //设定发送频率
        if(QDateTime::currentDateTime().toMSecsSinceEpoch()-lastTime.toMSecsSinceEpoch()<1000/Fre) //
        {
            continue;
        }
        lastTime=QDateTime::currentDateTime();
        if(modbus_read_registers(p_modbus,0,8,inputData)<0)
        {
            isConnect=false;
            break;
        }
        isConnect=true;

        //TODO:读取数据保存在结构体内
        s_HpData.Value=modbus_get_float(&inputData[0]);
        s_HpData.Up=modbus_get_float(&inputData[1]);
        s_HpData.Down=modbus_get_float(&inputData[2]);
        s_HpData.Compare=modbus_get_float(&inputData[3]);
        s_HpData.Acc=modbus_get_float(&inputData[4]);
        s_HpData.Range=inputData[5];
        s_HpData.unit=inputData[6];
        s_HpData.Rcords=inputData[7];

        if(isSetParam)
        {
            isSetParam=false;
            modbus_write_register(p_modbus,0,4);//设置参数
        }
    }
    isConnect=false;
    modbus_close(p_modbus);
    modbus_free(p_modbus);
}

void AcqPressure::delaymsec(int msec)
{
    qint64 dieTime = QDateTime::currentDateTime().toMSecsSinceEpoch();
    while( QDateTime::currentDateTime().toMSecsSinceEpoch()-dieTime < msec )
    {
        QCoreApplication::processEvents(QEventLoop::AllEvents,100);
        QThread::msleep(1);
    }
}


